package lgq.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lgq.service.CourseManager;
import model.Course;
import util.Page;

public class FindCourseServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
		int pageNo=1;
		int pageSize=10;
		String keycode="";
		// ���������������������request��ȡ���������session�л�ȡ����һ��Ϊnull��ô���ǻ�ȡȫ��
		if (null != request.getParameter("serchtype")) {
			request.getSession().setAttribute("serchtype",request.getParameter("serchtype"));
		}
		// ͬ���ж��Ƿ��д��������ؼ�֮�д�request��ȡû�д�sessionȡ��
		if (null != request.getParameter("keycode")) {
			request.getSession().setAttribute("keycode",request.getParameter("keycode"));
			keycode = request.getParameter("keycode");
		} else {
			keycode = (String) request.getSession().getAttribute("keycode");
		}
		try{
			if(request.getParameter("pageNo")!=null)
			{
				pageNo=Integer.parseInt(request.getParameter("pageNo"));
			}
			if(request.getParameter("pageSize")!=null)
			{
				pageSize=Integer.parseInt(request.getParameter("pageSize"));
				
				request.getSession().setAttribute("pageSize", pageSize);
			}
			if(request.getSession().getAttribute("pageSize")!=null)
			{
				pageSize=(Integer) request.getSession().getAttribute("pageSize");
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		Page<Course> page=null;
		if("name".equals(request.getSession().getAttribute("serchtype")))
		{
		page=new CourseManager().getByName(pageNo, pageSize,keycode);				
		}
		else if("courseid".equals(request.getSession().getAttribute("serchtype")))
		{
			try{
			Page<Course> p=new Page<Course>(1, 1);
			List<Course> list=new ArrayList<Course>();
			if(null!=new CourseManager().getById(Integer.parseInt(keycode)))
			{
				list.add(new CourseManager().getById(Integer.parseInt(keycode)));
				p.setList(list);
				p.setTotalCount(1);
			}					
			page=p;
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}else if("coursetime".equals(request.getSession().getAttribute("serchtype")))
		{
			try{
			page=new CourseManager().getByTime(pageNo, pageSize,Double.parseDouble(keycode));
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			page=new CourseManager().getAllCourse(pageNo, pageSize);
		}
		request.setAttribute("page", page);
		request.getRequestDispatcher("/Train/CourseManager.jsp").forward(request, response);
	}

}
